# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '24f41588f05c30c4af7eb1a41d845d2b': {
        #  领航支付 支付宝 2.5% 50—10000 dwc
        'API_KEY': 'cfeQf5A4oB6snr3h',
        'gateway': 'https://www.wftgs.cn/api/shopApi/order/createorder',
        'query_gateway': 'https://www.wftgs.cn/api/shopApi/order/queryorder',
    },
    '8564e0849d20eaa8cce75eda19a9cc3c': {
        #  领航支付 支付宝 2.5% 50—10000 tt
        'API_KEY': 'yjM6CizeGTqkrnQb',
        'gateway': 'https://www.wftgs.cn/api/shopApi/order/createorder',
        'query_gateway': 'https://www.wftgs.cn/api/shopApi/order/queryorder',
    },
    'c3b4cf233e874922a18953410fb54500': {
        #  领航支付 支付宝 2.5% 50—10000 zs
        'API_KEY': 'KnFnPLEN2Qx9HiDw',
        'gateway': 'https://www.wftgs.cn/api/shopApi/order/createorder',
        'query_gateway': 'https://www.wftgs.cn/api/shopApi/order/queryorder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_production_ip(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = '{}{}{}{}{}'.format(d['shop_id'], d['user_id'], d['money'], d['type'], key)
    return _gen_sign(s)


def generate_create_rsp_sign(d, app_id, key):
    s = '{}{}{}{}{}{}'.format(app_id, d['user_id'], d['order_no'], key, d['type'], d['money'])
    _LOGGER.info("linghangpay create response sign string is: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, app_id, key):
    s = '{}{}{}{}{}{}'.format(app_id, d['user_id'], d['order_no'], key, d['money'], d['type'])
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = '{}{}{}'.format(d['shop_id'], d['order_no'], key)
    return _gen_sign(s)


def verify_notify_sign(params, app_id, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, app_id, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("linghangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'wechat':
        return 'wechat'
    elif service == 'alipay':
        return 'alipay'
    elif service == 'unionpay':
        return 'unionpay'
    return 'alipay'


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("linghangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_create_sign(params, app_id, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_create_rsp_sign(params, app_id, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("linghangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '219.135.56.195'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('shop_id', app_id),
        ('user_id', pay.user_id),
        ('money', '%.2f' % pay_amount),
        ('type', _get_pay_type(service)),
        ('shop_no', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/linghangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("linghangpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['shop_no'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), json=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("linghangpay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)
    verify_create_sign(data, app_id, api_key)
    return {'charge_info': data['qrcode_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("linghangpay notify data: %s, order_id is: %s", data, data['shop_no'])
    verify_notify_sign(data, app_id, api_key)
    pay_id = data['shop_no']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('linghangpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['order_no']
    total_fee = float(data['money'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,0- 支付成功
    if trade_status == '0':
        _LOGGER.info('linghangpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('shop_id', app_id),
        ('order_no', pay_order.third_id),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("linghangpay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), json=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("linghangpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        verify_notify_sign(data, app_id, api_key)
        trade_status = str(data['status'])
        trade_no = str(data['order_no'])
        total_fee = float(data['money'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 0表示支付成功；1表示等待支付; 2表示支付超时；3表示支付失败；
        if trade_status == '0':
            _LOGGER.info('linghangpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('linghangpay data error, status_code: %s', response.status_code)
